

package com.yungu.swift.order.processor;

import com.alibaba.dubbo.config.annotation.Reference;
import com.yungu.swift.assets.passenger.model.dto.PassengerRechargeDto;
import com.yungu.swift.base.ResponseData;
import com.yungu.swift.constants.FinanceConstant;
import com.yungu.swift.constants.OrderConstant;
import com.yungu.swift.order.model.vo.PayVo;
import com.yungu.swift.system.finance.model.dto.FinanceActualFlowDto;
import com.yungu.swift.system.finance.model.dto.FinanceRechargeDto;
import com.yungu.swift.system.finance.service.FinanceActualFlowService;
import com.yungu.swift.system.finance.service.FinanceRechargeService;
import com.yungu.swift.system.sys.model.dto.SysAccountPassengerDto;
import com.yungu.swift.system.sys.model.dto.SysAccountPlatformDto;
import com.yungu.swift.system.sys.service.SysAccountPassengerService;
import com.yungu.swift.system.sys.service.SysAccountPlatformService;
import com.yungu.swift.utils.MapUtils;
import com.yungu.swift.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.support.TransactionTemplate;

import java.math.BigDecimal;
import java.util.Date;


/**
 * Created by cuixiuyin on 2018/5/8.
 */
@Component
public class PassengerRechargeDetailProcessor implements PayProcessor {

    private static final Logger logger = LoggerFactory.getLogger(PassengerRechargeDetailProcessor.class);

    @Reference
    private FinanceActualFlowService financeActualFlowService;
    @Reference
    private SysAccountPlatformService sysAccountPlatformService;
    @Reference
    private SysAccountPassengerService sysAccountPassengerService;
    @Reference
    private FinanceRechargeService financeRechargeService;
    @Autowired
    private TransactionTemplate transactionTemplate;

    @Override
    public void process(PayVo payVo) {
        logger.info("{} 乘客充值处理器开始处理---", payVo.getDescription());
        if (null == payVo.getPassengerRechargeDto()) {
            logger.info("{} 充值处理器-乘客充值模板为 null，处理器结束工作", payVo.getOrderRechargeUuid());
            return;
        }
        PassengerRechargeDto passengerRechargeDto = payVo.getPassengerRechargeDto();
        Double money = passengerRechargeDto.getMoney();
        Double giftMoney = passengerRechargeDto.getGift();
        BigDecimal rechargeAmount = new BigDecimal(null == money ? "0" : money.toString());
        BigDecimal giftAmount = new BigDecimal(null == giftMoney ? "0" : giftMoney.toString());

        //------------------------------------- 乘客充值支付 ----------------------------------------

        // 获取平台账户
        ResponseData<SysAccountPlatformDto> getPlatformAccount = sysAccountPlatformService.getByAppid(payVo.getAppid());
        if (!getPlatformAccount.isSuccess() || getPlatformAccount.getData() == null) {
            logger.info("充值处理器-获取平台账户[" + payVo.getAppid() + "]失败，处理器结束工作---");
            return;
        }
        SysAccountPlatformDto platformAccount = getPlatformAccount.getData();

        // 获取乘客账户
        ResponseData<SysAccountPassengerDto> getPassengerAccount = sysAccountPassengerService.get(MapUtils.build("uuid",
                payVo.getPassengerVo().getUuid()));
        if (!getPassengerAccount.isSuccess() || getPassengerAccount.getData() == null) {
            logger.info("充值处理器-获取乘客账户[" + payVo.getPassengerVo().getUuid() + "]失败，处理器结束工作---");
            return;
        }
        SysAccountPassengerDto passengerAccount = getPassengerAccount.getData();
        //获取乘客充值余额，赠送余额
        BigDecimal rechargeBalance = passengerAccount.getRechargeBalance();
        BigDecimal presentBalance = passengerAccount.getPresentBalance();

        Date nowDate = new Date();
        //现金支付发票
        FinanceActualFlowDto financeActualFlowDto = new FinanceActualFlowDto();
        financeActualFlowDto.setUuid(StringUtils.buildUUID());
        financeActualFlowDto.setAppid(payVo.getAppid());
        financeActualFlowDto.setOrderUuid(payVo.getOrderUuid());
        financeActualFlowDto.setType(FinanceActualFlowDto.TYPE_PASSENGER_RECHARGE);
        financeActualFlowDto.setPayType(payVo.getPayType());
        financeActualFlowDto.setMoney(rechargeAmount.doubleValue());
        String payTpeStr = "";
        if (payVo.getPayType() == OrderConstant.PAY_TYPE_TENPAY) {
            payTpeStr = "微信";
        }
        if (payVo.getPayType() == OrderConstant.PAY_TYPE_ALIPAY) {
            payTpeStr = "支付宝";
        }
        financeActualFlowDto.setRemark("乘客[" + StringUtils.right(payVo.getPassengerVo().getMobile(), 4) + "]通过[" + payTpeStr + "]支付" +
                rechargeAmount + "元，用于充值账户");
        financeActualFlowDto.setCreateBy(payVo.getUserUuid());
        financeActualFlowDto.setCreateOn(new Date());

        //增加乘客充值流水
        FinanceRechargeDto financeRechargeDto = new FinanceRechargeDto();
        financeRechargeDto.setUuid(StringUtils.buildUUID());
        financeRechargeDto.setAppid(payVo.getAppid());
        if (payVo.getPayType() == OrderConstant.PAY_TYPE_TENPAY) {
            financeRechargeDto.setCourse(FinanceConstant.TENPAY_RECHARGE);
        }
        if (payVo.getPayType() == OrderConstant.PAY_TYPE_ALIPAY) {
            financeRechargeDto.setCourse(FinanceConstant.ALIPAY_RECHARGE);
        }
        financeRechargeDto.setAmount(rechargeAmount);
        financeRechargeDto.setFinanceNumber(StringUtils.buildUUID());
        // 乘客 ——> 乘客账户
        financeRechargeDto.setFinanceInflow(passengerAccount.getUuid());
        financeRechargeDto.setFinanceOutflow(payVo.getPassengerVo().getUuid());
        financeRechargeDto.setDescription("乘客" + payTpeStr + "充值" + rechargeAmount + "元");
        financeRechargeDto.setBusinessUuid(payVo.getOrderRechargeUuid());
        financeRechargeDto.setHappenTime(nowDate);
        financeRechargeDto.setCreateOn(nowDate);
        financeRechargeDto.setCreateBy(payVo.getUserUuid());
        financeRechargeDto.setStartBalance(rechargeBalance);
        //修改乘客充值金额
        rechargeBalance = rechargeBalance.add(rechargeAmount);
        financeRechargeDto.setFinalBalance(rechargeBalance);


        //平台有赠送金额 则产生流水
        FinanceRechargeDto platformRecharge = new FinanceRechargeDto();
        if (giftAmount.doubleValue() > 0) {
            BigDecimal rewardAccumulate = platformAccount.getRewardAccumulate();
            platformRecharge.setUuid(StringUtils.buildUUID());
            platformRecharge.setAppid(payVo.getAppid());
            platformRecharge.setCourse(FinanceConstant.PRESENT_RECHARGE);
            platformRecharge.setAmount(giftAmount);
            platformRecharge.setFinanceNumber(StringUtils.buildUUID());
            // 平台 ——> 乘客赠送金额
            platformRecharge.setFinanceInflow(payVo.getPassengerVo().getUuid());
            platformRecharge.setFinanceOutflow(platformAccount.getUuid());
            platformRecharge.setDescription("乘客" + payTpeStr + "充值" + rechargeAmount + "元,平台赠送" + giftAmount + "元给乘客");
            platformRecharge.setBusinessUuid(payVo.getOrderRechargeUuid());
            platformRecharge.setHappenTime(nowDate);
            platformRecharge.setCreateOn(nowDate);
            platformRecharge.setCreateBy(payVo.getUserUuid());
            platformRecharge.setStartBalance(rewardAccumulate);
            //增加奖励累积
            rewardAccumulate = rewardAccumulate.add(rechargeAmount);
            platformRecharge.setFinalBalance(rewardAccumulate);


            //修改乘客赠送余额
            presentBalance = presentBalance.add(giftAmount);

            //修改平台账户信息 乘客充值的金额到乘客账户，所以平台现金余额不改变只改变奖励累积
            platformAccount.setRewardAccumulate(rewardAccumulate);
            platformAccount.setUpdateOn(nowDate);

        }

        //修改乘客账户信息
        passengerAccount.setPresentBalance(presentBalance);
        passengerAccount.setRechargeBalance(rechargeBalance);
        passengerAccount.setUpdateOn(nowDate);

        transactionTemplate.execute(transactionStatus -> {
            ResponseData<Boolean> addActualFlow = financeActualFlowService.add(financeActualFlowDto);
            if (addActualFlow.isSuccess() && addActualFlow.getData() != null && Boolean.TRUE.equals(addActualFlow.getData())) {
                logger.info("1、插入乘客充值发票流水成功,uuid:{}", financeActualFlowDto.getUuid());
            }
            ResponseData<Boolean> addRecharge = financeRechargeService.add(financeRechargeDto);
            if (addRecharge.isSuccess() && addRecharge.getData() != null && Boolean.TRUE.equals(addRecharge.getData())) {
                logger.info("2、插入乘客充值流水成功,uuid:{}", financeRechargeDto.getUuid());
            }
            if (StringUtils.isNotEmpty(platformRecharge.getUuid())) {
                ResponseData<Boolean> add = financeRechargeService.add(platformRecharge);
                if (add.isSuccess() && add.getData() != null && Boolean.TRUE.equals(add.getData())) {
                    logger.info("3、插入平台充值赠送流水成功,uuid:{}", platformRecharge.getUuid());
                }
                ResponseData<Boolean> edit = sysAccountPlatformService.edit(platformAccount);
                if (edit.isSuccess() && edit.getData() != null && Boolean.TRUE.equals(edit.getData())) {
                    logger.info("4、修改平台累计金额成功,uuid:{}", platformAccount.getUuid());
                }
            }
            ResponseData<Boolean> editPasAccount = sysAccountPassengerService.edit(passengerAccount);
            if (editPasAccount.isSuccess() && editPasAccount.getData() != null && Boolean.TRUE.equals(editPasAccount.getData())) {
                logger.info("5、修改乘客余额成功,uuid:{}", passengerAccount.getUuid());
            }
            return Boolean.TRUE;
        });
        logger.info("{}--处理乘客充值账户流水逻辑完毕", payVo.getDescription());
    }

}
